<template>
  <div class="page-content">
    <el-row :gutter="12">
      <el-col :xs="24" :sm="12" :lg="8">
        <el-input placeholder="部门名称"></el-input>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="8" class="el-col2">
        <el-button v-ripple>搜索</el-button>
        <el-button @click="showDialog('add')" v-ripple>新增部门</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData">
      <template #default>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="sort" label="排序" sortable />
        <el-table-column prop="create_time" label="创建日期" />
        <el-table-column fixed="right" label="操作" width="150px">
          <template #default="scope">
            <button-table type="edit" @click="showDialog('edit', scope.row)" />
            <button-table type="delete" @click="deleteDepartment(scope.row)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门' : '编辑部门'"
      width="30%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <el-select v-model="formData.parent_id">
            <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import {DeptService} from '@/api/user/deptApi'
  import {toTreeData} from '@/utils/utils'

  const dialogType = ref('add')
  const dialogVisible = ref(false)

  const formData = reactive({
    name: '',
    sort: '1',
    parent_id:''
  })

  const deptList = ref([])
  const tableData = ref([])

  const formRef = ref<FormInstance>()

  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入部门名称', trigger: 'blur' },
    ],
    parent_id: [
      { required: true, message: '请选择上级部门', trigger: 'blur' },
    ]
  })

  const resetForm = () => {
    formData.name = ''
    formData.sort = '1'
  }

  getDeptPage()
  // 获取分页
  async function getDeptPage() {
    const res = await DeptService.getDeptList()
    formData.parent_id = res.data[0].id
    deptList.value = res.data
    tableData.value = toTreeData({
      data: res.data,
      idField: 'id',
      parentIdField: 'parent_id',
      addParentIds: true,
      parentIds: []
    })
  }

  const showDialog = (type: string, row?: any) => {
    dialogType.value = type
    dialogVisible.value = true

    if (type === 'edit' && row) {
      formData.name = row.name
      formData.parent_id = row.id
      formData.sort = row.sort.toString()
    } else {
      resetForm()
    }
  }

  const deleteDepartment = (row:any) => {
    ElMessageBox.confirm('确定要删除该部门吗？', '删除部门', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      DeptService.deptDelete({id:row.id})
      ElMessage.success('删除成功')
    }).finally(() => {
      getDeptPage()
    })
  }

  const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        if(dialogType.value === 'add') {
          await DeptService.deptCreate(toRaw(formData))
        } else {
          await DeptService.deptUpdate(toRaw(formData))
        }
        await getDeptPage()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }
  }
</style>
